<template>
  <div class="user">
    <basic-container>
      <avue-crud
        ref="crud"
        :option="option"
        v-model="form"
        :page="page"
        :table-loading="listLoading"
        :before-open="handleOpenBefore"
        :data="list"
        @on-load="getList"
        @search-change="handleFilter"
        @refresh-change="handleRefreshChange"
        @search-reset="searchReset"
        @row-update="update"
        @row-save="create"
      >
        <template slot="username" slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
        <template slot="role" slot-scope="scope">
          <span v-for="(role, index) in scope.row.roleList" :key="index">
            <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
          </span>
        </template>
        <template slot="deptId" slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
        <template slot="lockFlag" slot-scope="scope">
          <el-tag>{{ scope.label }}</el-tag>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            v-if="sys_user_edit"
            type="text"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, scope.index)"
            >编辑
          </el-button>
        </template>
        <template slot="roleForm" slot-scope="scope">
          <avue-select
            v-model="role"
            :dic="rolesOptions"
            :props="roleProps"
            placeholder="请选择角色"
          />
        </template>

        <template slot="deviceOperateNoForm">
          <el-select v-model="form.deviceOperateNo" placeholder="请选择" filterable>
            <el-option
              v-for="item in deviceList"
              :key="item.operationCode"
              :label="item.operationCode"
              :value="item.operationCode"
            >
            </el-option>
          </el-select>
        </template>
        
        <template slot="manageStationsForm" slot-scope="scope">
          <dynamic-crud
            title="管理线路与站点"
            :data="form.manageStations"
            :option="stationsOption"
            :disabled="window.boxType == 'views'"
          >
          </dynamic-crud>
        </template>    
        <template slot="menuLeft">
           <el-button
                class="filter-item"
                type="primary"
                size="mini"                
                @click="editPWD"
                v-if="sys_user_edit"
                >批量初始密码
              </el-button>	   
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"               
                @click="editEnable('0')"
                v-if="sys_user_edit"
                >批量启用用户
              </el-button>
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"              
                @click="editEnable('9')"
                v-if="sys_user_edit"
                >批量锁定用户
              </el-button>	     
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"              
                @click="editEnable('8')"
                v-if="sys_user_edit"
                >批量禁用用户
              </el-button>
	   <!-- <el-upload
            class="upload-inline"
            action=""
            :show-file-list="false"
            accept=".xls,.xlsx"
            :http-request="handleImportJD"
          >
            <el-button type="primary" size="small">导入</el-button>
          </el-upload> -->
        </template>
       <!--  <template slot="menuRight">
          <el-button
            @click="handleDownloadClickJD"
            type="text"
            size="small"
          >模板下载</el-button>
        </template> -->
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  addObj,
  delObj,
  fetchList,
  putObj,
  saveBatch,
  getUserDeviceNoByConditionLC,
  templateJD,
  userImportJD,
  updateBatch,
  updateBatchLock
} from "@/api/admin/user";
import { deptRoleList } from "@/api/admin/role";
import { tableOption } from "@/const/crud/admin/userJD";
import { handleExcelResponse } from "@/util/util";
import { mapGetters } from "vuex";

export default {
  name: "SysUserLC",
  data() {
    return {
      window: window,
      searchForm: {},
      option: tableOption,
      roleProps: {
        label: "roleName",
        value: "roleId"
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false // 是否倒序
      },
      list: [],
      listLoading: true,
      role: [],
      form: {},
      rolesOptions: [],
      deviceList: [],
      stationsOption: {
        column: [
          {
            label: "线路",
            prop: "line",
            type: "select",
            cascaderItem: ["station"],
            props: {
              label: "name",
              value: "code"
            },
            dicUrl: "/support/swparamline/dict",
            cell: true,
            rules: [{ required: true, message: "请选择线路", trigger: "blur" }]
          },
          {
            label: "站点",
            prop: "station",
            type: "select",
            dicFlag: false,
            props: {
              label: "name",
              value: "code"
            },
            dicUrl: "/support/swparamstation/dict/{{key}}",
            cell: true
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  watch: {
    role() {
      this.form.role = this.role ? [this.role] : [];
    },
    "form.belongToLine"(val) {
      this.findObject(this.option.column, "lineCode").display = !val;
      this.findObject(this.option.column, "stationCode").display = !val;
      this.findObject(this.option.column, "deviceOperateNo").display = !val;

      //如果是非线网人员，也可以设置管辖线路
      //this.findObject(this.option.column, "isManageStation").display = val;
      if (val) {
        // 线网人员，线路,车站和设备操作号为空
        this.form.lineCode = null;
        this.form.stationCode = null;
        this.form.deviceOperateNo = null;
      } else {
        if (this.validatenull(this.form.manageStations)) {
          this.form.managementLineStation = null;
          this.form.isManageStation = false;
        }else{
          this.form.isManageStation = true;
        }
      }
    },
    "form.isManageStation"(val) {
      this.findObject(this.option.column, "manageStations").display = val;
    }
  },
  created() {
    this.sys_user_add = this.permissions["sys_user_add"];
    this.sys_user_edit = this.permissions["sys_user_edit"];
    this.sys_user_del = this.permissions["sys_user_del"];

    const that = this;
    this.option.column[8].change = function(row, col) {
      that.form.deviceOperateNo = "";
      that.deviceList = [];
    };
    this.option.column[9].change = function(row, col) {
      const lineCode = that.form.lineCode;
      const stationCode = row.value;
      if (lineCode && stationCode) {
        getUserDeviceNoByConditionLC(lineCode, stationCode).then(res => {
          if (res && res.data.data.records.length) {
            that.deviceList = res.data.data.records;
          }
        });
      } else {
        that.form.deviceOperateNo = "";
        that.deviceList = [];
      }
    };
  },
  methods: {
    getList(page, params) {
      this.listLoading = true;
      return fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
            flag: "JD"
          },
          params,
          this.searchForm
        )
      ).then(response => {
        let records = response.data.data.records;
        records.forEach(r => {
          if (r.managementLineStation) {
            r.isManageStation = true;
            r.manageStations = JSON.parse(r.managementLineStation);
            r.manageStations.forEach(s => {
              s.$cellEdit = true;
            });
          } else {
            r.isManageStation = false;
            r.manageStations = [];
          }
        });
        this.list = records;
        this.page.total = response.data.data.total;
        this.listLoading = false;
      });
    },
    handleFilter(param, done) {
      this.searchForm = param;
      this.getList(this.page, param).then(() => {
        done();
      });
    },
    // handleImport(item) {
    //   let file = item.file;
    //   let param = new FormData();
    //   param.append("file", file);
    //   saveBatch(param).then(() => {
    //     this.$notify({
    //       title: "成功",
    //       message: "导入成功",
    //       type: "success",
    //       duration: 2000
    //     });
    //     this.getList(this.page);
    //   });
    // },
    async handleDownloadClickJD () {//机电人员导出模板
      this.uploading = true;
      try {
        const res = await templateJD();
        handleExcelResponse(res);
      } finally {
        this.uploading = false;
      }
    },
    handleImportJD(item) {//机电人员导入
      this.$message.info("正在导入，请耐心等待！");
      let file = item.file;
      let param = new FormData();
      param.append("file", file);
      userImportJD(param).then(() => {
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
          duration: 2000
        });
        this.getList(this.page);
      });
    },
    handleRefreshChange() {
      this.getList(this.page);
    },
    handleCreate() {
      this.$refs.crud.rowAdd();
    },
    handleOpenBefore(show, type) {
      window.boxType = type;
      if (["edit", "views"].includes(type)) {
        for (var i = 0; i < this.form.roleList.length; i++) {
          this.role = this.form.roleList[i].roleId;
          this.form.role = [this.role];
        }
      } else if (type === "add") {
        this.role = null;
      }
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data;
        const roles = this.rolesOptions.filter(
          w =>
            w.roleCode == "JDJSZL" ||
	    w.roleCode == "JDJSZB" ||
	    w.roleCode == "JDZHJXBZ" ||
	    w.roleCode == "JDJXG" ||
            w.roleCode == "JDZHWXG" ||
            w.roleCode == "JDZHJXG" ||
            w.roleCode == "ZPSZR"
        );
        this.rolesOptions = roles;
      });
      show();
    },
    searchReset(form) {
      for (let key of Object.keys(form)) {
        if (this.validatenull(form[key])) {
          delete form[key];
        }
      }
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleUpdate(row, index) {
      this.$confirm("修改时记得修改对应线路所属部门?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          this.$refs.crud.rowEdit(row, index);
          this.form.password = undefined;
      });
    },
    create(row, done, loading) {
      // if (this.form.phone.indexOf('*') > 0) {
      //     this.form.phone = undefined
      // }
      if (this.validatenull(this.form.manageStations)) {
        this.form.managementLineStation = null;
      } else {
        let lineStations = this.form.manageStations.map(r => {
          return {
            line: r.line,
            station: r.station
          };
        });
        this.form.managementLineStation = JSON.stringify(lineStations);
      }
      delete this.form.manageStations;
      delete this.form.dates1;
      addObj(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify({
            title: "成功",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        })
        .catch(() => {
          loading();
        });
    },
    update(row, index, done, loading) {
      // if (this.form.phone && this.form.phone.indexOf('*') > 0) {
      //     this.form.phone = undefined
      // }
      if (this.validatenull(this.form.manageStations)) {
        this.form.managementLineStation = null;
      } else {
        let lineStations = this.form.manageStations.map(r => {
          return {
            line: r.line,
            station: r.station
          };
        });
        this.form.managementLineStation = JSON.stringify(lineStations);
      }
      delete this.form.manageStations;
      delete this.form.dates1;
      putObj(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        })
        .catch(() => {
          loading();
        });
    },
     //变更启动、禁用 、锁定   flag ：  8 禁用  0：启用
	    editEnable(flag){     
	      if (this.$refs.crud.tableSelect.length < 1) {
		this.$message.error("请选择数据");
		return false;
	      }
	      let tipValue ="禁用";
	      if(flag == '0'){
		  tipValue = "启用";
	      }
	      if(flag == '9'){
		  tipValue = "锁定";
	      }
	      let ids = [];
	      for (const table of this.$refs.crud.tableSelect) {
		ids.push(table.userId);
	      }
	      if(ids==null || ids.length==0 ){
		return;
	      }
	      this.$confirm("确认"+tipValue+"?", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning"
	      }).then(() => {
		 let str = ids.join(','); // 使用逗号作为分隔符
		 updateBatchLock(str,flag)
		  .then(data => {
		    this.$message.success(tipValue+"成功");
		    done();
		  })
		  .catch(() => {
		    loading();
		  });
		  this.getList(this.page);
	      });
	    },
	    editPWD: function() {
	      if (this.$refs.crud.tableSelect.length < 1) {
		this.$message.error("请选择数据");
		return false;
	      }
	      let ids = [];
	      for (const table of this.$refs.crud.tableSelect) {
		ids.push(table.userId);
	      }      
	      if(ids==null || ids.length==0 ){
		return;
	      }
	      this.$confirm("确认修改?", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning"
	      }).then(() => {
		let str = ids.join(','); // 使用逗号作为分隔符
		updateBatch(str)
		  .then(data => {
		    this.$message.success("修改成功");
		    done();
		  })
		  .catch(() => {
		    loading();
		  });
		 this.getList(this.page);
	      });
	    },
    deletes(row, index) {
      this.$confirm(
        "此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        delObj(row.userId)
          .then(() => {
            this.list.splice(index, 1);
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
          })
          .cache(() => {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "error",
              duration: 2000
            });
          });
      });
    }
  }
};
</script>
<style lang="scss">
.user {
  height: 100%;

  &__tree {
    padding-top: 3px;
    padding-right: 20px;
  }

  &__main {
    .el-card__body {
      padding-top: 0;
    }
  }
}
</style>
